package thenewscats;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;

/*
 * A servlet dedicated to working on creating an article
 * This is a workaround to the fact that blobstore's createUploadURL
 */
		
@SuppressWarnings("serial")
public class createArticleServlet extends HttpServlet {
	/* used for images */
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	public void doPost (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		doCreate (req, resp);
	}
	
	public void doGet (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		doCreate (req, resp);
	}
	
	protected void doCreate (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		
		// Get blob key
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
	    BlobKey blobKey = blobs.get("articleImage");        
		
		String title = req.getParameter ("title");
		String author = req.getParameter ("author");
		String subtitle = req.getParameter ("subtitle");
		String category = req.getParameter ("category");
		String content = req.getParameter ("articleText");	
		
		category = category.toLowerCase();
				
		// Create article
		Article a = new Article (title, author, subtitle, category, content);
		a.setImageKey(blobKey);
		
		// commit to persistence manager
		ArticleFactory af = ArticleFactory.getInstance();
		af.saveArticle(a);
		
		String keystring = KeyFactory.keyToString(a.getKey());
		
		// Must send instead of forwards because of blobstore
		String redirect = "article?action=view&articlekey=" + keystring;
		redirect = redirect + "&create=true"; // just recently created 
		resp.sendRedirect(redirect);
	}
}
